var express = require('express');
var router = express.Router();

/* GET users listing. */
router.get('/', function(req, res, next) {
  	req.popo.find().toArray(function(err, items){
		res.render('map',{'title':'popo工厂','user':req.infos,'popos':items});
	});
});

router.get('/:id',function(req,res,next) {
	req.users.findById(req.params.id,function(err, result) {
		if (err) {
			return next(new Error('users error'));
		} else {
			res.jsonp({'write':result});
		}
	});
});

router.post('/',function(req,res,next) {
	if (!req.popo ) 
		return next(new Error('popo object not find'));
    req.popo.find({"ip":req.body.mypopo.ip}).toArray(function(err,items) {
    	if (items.length>0) {
    		req.popo.update({"ip":req.body.mypopo.ip},req.body.mypopo,function(err,items) {
    		res.redirect('/map');
    		});
    	} else {
    		req.popo.insertOne(req.body.mypopo, function(){
			res.redirect('/map');
			});
    	}
    });

});

module.exports = router;
